<template>
  <div class="shared-resources">
    <!-- 顶部选项卡 -->
<el-card class="tab-card" shadow="hover">
  <el-tabs v-model="activeTab" @tab-change="handleTabChange">
    <el-tab-pane label="全部资源" name="all" />
    <!-- 新增：我的资源选项卡 -->
    <el-tab-pane label="我的资源" name="my" />
  </el-tabs>
</el-card>

    <!-- 搜索区域 -->
    <el-card class="filter-card" shadow="hover">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-input
            v-model.lazy="searchKeyword"
            placeholder="搜索课程标题"
            clearable
            size="large"
            @clear="handleFilterChange"
            @change="handleFilterChange"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <!-- 上传按钮 -->
        <el-col :xs="12" :sm="6" :md="2" :lg="2">
          <el-button 
            type="primary" 
            size="large" 
            @click="showUploadDialog = true"
          >
            <el-icon><Upload /></el-icon>
            上传课程
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 课程列表 -->
    <el-card class="resource-list-card" shadow="hover">
      <template #header>
        <div class="list-header">
          <span class="header-title">课程资源</span>
          <span class="resource-count">共 {{ filteredCourses.length }} 个课程</span>
          <div class="header-actions">
            <el-tooltip content="刷新列表" placement="top">
              <el-button :icon="Refresh" circle @click="fetchCourseList" />
            </el-tooltip>
          </div>
        </div>
      </template>

      <el-table
        :data="paginatedCourses"
        style="width: 100%"
        stripe
        v-loading="loading"
        :row-key="row => row.id"
      >
        <el-table-column prop="title" label="课程标题" min-width="300" />
        
        <el-table-column prop="userNum" label="上传用户编号" width="150" />
        
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.createdAt) }}
          </template>
        </el-table-column>
        
<!-- 课程列表的操作列（修改后） -->
<el-table-column label="操作" width="200" fixed="right">
  <template #default="{ row }">
    <el-button-group>
      <!-- 查看文件按钮：所有选项卡都显示 -->
      <el-tooltip content="查看文件" placement="top">
        <el-button
          type="primary"
          size="small"
          @click="viewCourseFiles(row.id)"
          :icon="View"
          circle
        />
      </el-tooltip>
      
      <!-- 删除课程按钮：仅“我的资源”选项卡显示（添加v-if条件） -->
      <el-tooltip content="删除课程" placement="top" v-if="activeTab === 'my'">
        <el-button
          type="danger"
          size="small"
          @click="deleteCourse(row.id)"
          :icon="Delete"
          circle
        />
      </el-tooltip>
    </el-button-group>
  </template>
</el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="filteredCourses.length"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          :hide-on-single-page="filteredCourses.length <= 10"
        />
      </div>
    </el-card>

    <!-- 课程文件查看对话框 -->
  <el-dialog
    v-model="fileDialogVisible"
    title="课程详情与文件列表"
    width="80%"  
    :before-close="handleFileDialogClose" 
  >
    <!-- 新增：课程基础信息展示卡片 -->
    <el-card class="course-detail-card" shadow="hover">
      <div class="course-header">
        <!-- 用户头像 + 基本信息 -->
        <div class="user-info">
          <el-avatar :src="courseDetail.avatar" size="60">
            <!-- 头像加载失败时显示用户编号首字符 -->
            <span class="avatar-placeholder">{{ getAvatarPlaceholder(courseDetail.userNum) }}</span>
          </el-avatar>
          <div class="user-meta">
            <p class="user-num">上传用户：{{ courseDetail.userNum || '未知用户' }}</p>
            <p class="create-time">创建时间：{{ formatTime(courseDetail.createdAt) || '未知时间' }}</p>
          </div>
        </div>
      </div>

      <!-- 课程标题 + 内容 -->
      <div class="course-content" style="margin-top: 15px;">
        <h3 class="course-title">{{ courseDetail.title || '未命名课程' }}</h3>
        <div class="course-desc">
          <span class="desc-label">课程简介：</span>
          <p class="desc-content">{{ courseDetail.content || '暂无课程简介' }}</p>
        </div>
      </div>
    </el-card>

    <!-- 原有文件列表（保留，调整样式适配） -->
    <el-table
      :data="courseFiles"
      style="width: 100%"
      stripe
      v-loading="fileLoading"
      :empty-text="courseFiles.length === 0 ? '该课程暂无关联文件' : '加载中...'"
    >
      <el-table-column prop="fileName" label="文件名" min-width="250" />
      <el-table-column prop="fileType" label="文件类型" width="120">
        <template #default="{ row }">
          {{ formatFileType(row.fileType) }}
        </template>
      </el-table-column>
      <el-table-column prop="fileSize" label="文件大小" width="150">
        <template #default="{ row }">
          {{ formatFileSize(row.fileSize) }}
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="上传时间" width="180" />
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
          <el-button
            type="success"
            size="small"
            @click="downloadFile(row.id)"
            :icon="Download"
            
          >
            下载
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>

<!-- 上传课程对话框 -->
<el-dialog
  v-model="showUploadDialog"
  title="上传课程"
  width="60%"
>
  <el-form 
    ref="uploadFormRef"
    :model="uploadForm" 
    label-width="100px"
    :rules="formRules"
  >
    <el-form-item label="课程标题" prop="title">
      <el-input v-model="uploadForm.title" placeholder="请输入课程标题" />
    </el-form-item>
    <el-form-item label="课程内容">
      <el-input
        v-model="uploadForm.content"
        type="textarea"
        rows="5"
        placeholder="请输入课程内容"
      />
    </el-form-item>
    <el-form-item label="上传文件">
      <el-upload
        v-model:file-list="fileList"
        action=""
        :auto-upload="false"
        :on-change="handleFileChange"
        multiple
        ref="uploadRef"
      >
        <el-button type="primary">选择文件</el-button>
        <template #tip>
          <div class="el-upload__tip">支持多文件上传</div>
        </template>
      </el-upload>
    </el-form-item>
  </el-form>
  <template #footer>
    <el-button @click="showUploadDialog = false">取消</el-button>
    <el-button type="primary" @click="submitUpload">确认上传</el-button>
  </template>
</el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { Search, Upload, Refresh, View, Delete, Download } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  getCourseList, 
  getCourseFile, 
  deleteCourse as deleteCourseApi, 
  insertCourse,
  getCourseDetails,
  getCourseListByUserNum
} from '../../../../api/course/course.js';
import { useLoginStore } from '../../../../stores/index.js'

// 状态管理
const activeTab = ref('all');
const loading = ref(false);
const fileLoading = ref(false);
const searchKeyword = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const showUploadDialog = ref(false);
const fileDialogVisible = ref(false);
const uploadFormRef = ref(null);
const loginStore = useLoginStore()
const isMyResource = ref(false);

// 数据管理
const courseList = ref([]);
const courseFiles = ref([]);
const fileList = ref([]);
const uploadForm = ref({
  title: '',
  content: '',
  userNum: loginStore.user.number
});
// 在脚本中添加表单验证规则

const formRules = ref({
  title: [
    { required: true, message: '请输入课程标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  content: [
    { max: 500, message: '课程内容不能超过 500 个字符', trigger: 'blur' }
  ]
});

// 过滤后的课程列表
const filteredCourses = computed(() => {
  return courseList.value.filter(course => {
    const matchKeyword = course.title.includes(searchKeyword.value);
    const matchMyResource = isMyResource.value 
      ? course.userNum === loginStore.user.number 
      : true;
    
    return matchKeyword && matchMyResource;
  });
});
const courseDetail = ref({
  title: '',
  content: '',
  createdAt: null,
  userNum: '',
  avatar: ''
});

    const downloadFile = (fileId) => {
        try {
            // 1. 根据fileId找到当前要下载的文件
            const targetFile = courseFiles.value.find(courseFiles => courseFiles.id === fileId);
            if (!targetFile) { // 若未找到文件，提示错误
                ElMessage.error('未找到该文件，无法下载');
                return;
            }

            // 2. 获取文件的真实下载URL和文件名
            const fileUrl = targetFile.filePath;
            const fileName = targetFile.fileName || '未知文件名';

            console.log('fileUrl', fileUrl);

            if (!fileUrl) {
                ElMessage.error('文件地址无效，无法下载');
                return;
            }

            // 3. 声明并创建<a>标签（修复a未定义的核心）
            const a = document.createElement('a');
            a.href = fileUrl; // 设置文件下载地址
            a.download = fileName; // 设置下载后的文件名
            a.target = '_blank'; // 避免部分浏览器拦截下载

            // 4. 触发下载（需将a标签临时添加到DOM中，部分浏览器要求DOM存在才能触发点击）
            document.body.appendChild(a);
            a.click(); // 模拟点击下载

            // 5. 下载后清理DOM（移除临时创建的a标签）
            document.body.removeChild(a);
            ElMessage.success('文件开始下载');
        } catch (error) {
            // 捕获异常，避免页面崩溃
            ElMessage.error('下载失败，请稍后重试');
            console.error('文件下载错误：', error);
        }
    };

// 格式化文件类型（若接口返回MIME类型，提取后缀）
const formatFileType = (fileType) => {
  if (!fileType) return '未知类型';
  // 情况1：若fileType是MIME类型（如application/pdf），提取最后一个“/”后的内容
  if (fileType.includes('/')) {
    return fileType.split('/')[1].toUpperCase() + ' 文件';
  }
  // 情况2：若fileType是直接后缀（如pdf），直接格式化
  return fileType.toUpperCase() + ' 文件';
};

// 分页处理
const paginatedCourses = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  return filteredCourses.value.slice(startIndex, startIndex + pageSize.value);
});

// 格式化时间
const formatTime = (time) => {
  return new Date(time).toLocaleString();
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1048576) return `${(bytes / 1024).toFixed(2)} KB`;
  return `${(bytes / 1048576).toFixed(2)} MB`;
};

// 获取课程列表
const fetchCourseList = async () => {
  try {
    loading.value = true;
    let res;
    // 判断选项卡：全部资源→调用getCourseList；我的资源→调用getCourseListByUserNum
    if (activeTab.value === 'my') {
      // 我的资源：传入当前登录用户编号（从loginStore获取）
      res = await getCourseListByUserNum(loginStore.user.number);
      // 标记为“我的资源”模式
      isMyResource.value = true;
    } else {
      // 全部资源：调用原接口
      res = await getCourseList();
      // 标记为“全部资源”模式
      isMyResource.value = false;
    }
    // 赋值到课程列表（保持原逻辑）
    courseList.value = res;
  } catch (error) {
    ElMessage.error('获取课程列表失败：' + (error.message || '网络错误'));
  } finally {
    loading.value = false;
  }
};

// 获取课程文件
const viewCourseFiles = async (courseId) => {  // 参数名改为courseId，语义更清晰
  try {
    fileLoading.value = true;
    // 第一步：先调用getCourseDetails获取课程基础信息
    const detailRes = await getCourseDetails(courseId);
    courseDetail.value = detailRes;  // 赋值到课程详情变量

    // 第二步：再调用getCourseFile获取该课程的文件列表
    const filesRes = await getCourseFile(courseId);
    courseFiles.value = filesRes;

    // 打开对话框
    fileDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('加载课程数据失败：' + (error.message || '网络错误'));
  } finally {
    fileLoading.value = false;
  }
};

// 3. 新增：关闭文件对话框时清空数据（避免下次打开显示旧数据）
const handleFileDialogClose = () => {
  courseDetail.value = {
    title: '',
    content: '',
    createdAt: null,
    userNum: '',
    avatar: ''
  };
  courseFiles.value = [];
  fileDialogVisible.value = false
  
};

// 4. 新增：头像加载失败时的占位符（取用户编号首字符）
const getAvatarPlaceholder = (userNum) => {
  if (!userNum) return '未';
  return userNum.charAt(0).toUpperCase();  // 取首字符并大写
};

// 删除课程
const deleteCourse = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该课程吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    await deleteCourseApi(id);
    ElMessage.success('删除成功');
    fetchCourseList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + (error.message || '网络错误'));
    }
  }
};

// 处理文件上传
const handleFileChange = (file, fileList) => {
  // 控制文件列表
  fileList.value = fileList;
};

const submitUpload = async () => {
  // 验证表单
  if (!uploadFormRef.value) return;
  
  try {
    // 使用async/await方式处理验证
    await uploadFormRef.value.validate();
    
    if (fileList.value.length === 0) {
      ElMessage.warning('请选择至少一个文件');
      return;
    }

    await insertCourse(uploadForm.value, fileList.value.map(f => f.raw));
    ElMessage.success('上传成功');
    showUploadDialog.value = false;
    fileList.value = [];
    uploadForm.value = { title: '', content: '', userNum: uploadForm.value.userNum };
    fetchCourseList();
  } catch (error) {
    // 表单验证失败会进入这里
    if (error.name !== 'ValidationError') {
      ElMessage.error('上传失败：' + (error.message || '网络错误'));
    }
  }
};

// 筛选变化处理
const handleFilterChange = () => {
  currentPage.value = 1;
};

// 选项卡变化处理
const handleTabChange = () => {
  currentPage.value = 1;
  fetchCourseList();
};

// 页面加载时获取数据
onMounted(() => {
  fetchCourseList();
});
</script>

<style scoped>
/* 1. 全局容器样式 */
.shared-resources {
  padding: 15px;
}

/* 2. 卡片基础样式（选项卡、筛选、列表） */
.tab-card, .filter-card {
  margin-bottom: 15px;
  padding: 15px;
}

.resource-list-card {
  padding: 15px;
}

/* 3. 列表头部样式 */
.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 16px;
  font-weight: bold;
}

.resource-count {
  color: #666;
  margin-left: 10px;
}

/* 4. 分页样式 */
.pagination-wrapper {
  margin-top: 15px;
  text-align: right;
}

/* 5. 课程详情卡片样式（对话框内） */
.course-detail-card {
  margin-bottom: 20px;
  padding: 20px;
}

.course-header {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-meta {
  line-height: 1.6;
}

.user-num {
  font-weight: 500;
  color: #333;
}

.create-time {
  color: #666;
  font-size: 14px;
}

.course-content {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #eee;
}

.course-title {
  font-size: 18px;
  color: #2c3e50;
  margin-bottom: 10px;
}

.desc-label {
  font-weight: 500;
  color: #444;
  display: inline-block;
  margin-bottom: 5px;
}

.desc-content {
  color: #666;
  line-height: 1.8;
  white-space: pre-wrap;
  background-color: #f9fafb;
  padding: 10px 15px;
  border-radius: 4px;
  min-height: 60px;
}

/* 6. 表格空状态样式 */
.el-table__empty-text {
  color: #999;
  font-size: 14px;
}
</style>